package dao;

import model.History;

import java.sql.Timestamp;
import java.util.List;

/**
 * 历史记录的底层操作
 */
public class HistoryDAO {
    /**
     * 查询浏览历史
     *
     * @param userName 用户名
     * @return list
     */
    public List<History> getUserHistory(String userName) {
        List<History> list = null;
        String sql = "select * from history where user_name=? order by time desc";//根据时间排序
        Object[] params = {userName};
        list = DAO_common.beanListQuery(sql, History.class, params);
        return list;
    }

    /**
     * 增加历史的操作
     *
     * @param userName  用户名
     * @param comicId   漫画id
     * @param chapterId 章节id
     */
    public void addHistory(String userName, int comicId, int chapterId) {

        Timestamp time = new Timestamp(System.currentTimeMillis());
        addHistory(userName, comicId, chapterId, time);

    }

    /**
     * 增加历史的操作
     *
     * @param userName  用户名
     * @param comicId   漫画id
     * @param chapterId 章节id
     * @param time      时间戳
     */
    public void addHistory(String userName, int comicId, int chapterId, Timestamp time) {
        Object[] params = {userName, comicId, chapterId, time};
        String sql = "CALL insertHistory(?,?,?,?);";//这个存储过程控制了历史记录条数，有则更新，无则插入

        int count = DAO_common.updateQuery(sql, params);//调用存储过程,写在了mysql存储过程中
        System.out.println("CALL 存储过程:" + count);
    }

    /**
     * 查询有无这个历史记录
     *
     * @param userName 用户名
     * @param comicId  漫画id
     * @return History
     */
    public History checkHistory(String userName, int comicId) {
        History history;
        String sql = "select * from history where user_name=? and comic_id=?";
        Object[] params = {userName, comicId};
        history = DAO_common.beanQuery(sql, History.class, params);
        return history;
    }

    /**
     * 删除某个history
     *
     * @param userName 用户名
     * @param comicId  漫画id
     * @return true表示成功
     */
    public boolean deleteHistory(String userName, int comicId) {
        String sql = "delete from history where user_name=? and comic_id=?";
        Object[] params = {userName, comicId};
        int row = DAO_common.updateQuery(sql, params);
        return row > 0;
    }
}
